package com.itcast.controller;

import com.itcast.pojo.User;
import com.itcast.service.UserService;
import com.itcast.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UserService userService = new UserServiceImpl();
        String userId = request.getParameter("userName");
        String password = request.getParameter("password");
        System.out.println(userId + password);
        HttpSession session = request.getSession();
        User user = userService.findUserByUserIdAndPassword(userId, password);
        if (user == null) {
            request.setAttribute("mag", "用户名或密码错误！");
            request.getRequestDispatcher("/page/login.jsp").forward(request, response);
        } else {
            request.setAttribute("msg", "登录成功！");
            User user1 = userService.findByUserId(user.getUserId());
            session.setAttribute("user", user1);
            response.sendRedirect(getServletContext().getContextPath() + "/" + "findFriendServlet");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
